package com.jie.commonlib.utils;

import android.util.Base64;

import com.blankj.utilcode.util.LogUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/**
 * des加密/解密工具类
 * @author jie
 */
public class DesUtil {

    private static final String ALGORITHM = "DES";
    private static final String CIPHER_PARAM = "DES/ECB/PKCS5Padding";

    /**
     * 加密 外部调用
     *
     * @param srcStr 待加密的字符串
     * @param sKey 加密key
     * @return
     */
    public static String encrypt(String srcStr, String sKey) {
        byte[] src = srcStr.getBytes();
        byte[] buf = encrypt(src, sKey);
//        return parseByte2HexStr(buf);
        if (buf != null){
            return Base64.encodeToString(buf,Base64.NO_WRAP);
        }else{
            LogUtils.i("des加密失败：" + srcStr);
            return null;
        }
    }

    /**
     * 解密 外部调用
     *
     * @param srcStr 加密后的base64字符串
     * @param sKey 加密key
     * @return
     */
    private static String decrypt(String srcStr, String sKey) {
        byte[] src = Base64.decode(srcStr, Base64.NO_WRAP);
        byte[] buf = decrypt(src, sKey);
        if (buf != null){
            return new String(buf);
        }else{
            LogUtils.i("des解密失败：" + srcStr);
            return null;
        }
    }

    /**
     * ECB模式加密 内部调用
     *
     * @param data
     * @param sKey
     * @return
     */
    private static byte[] encrypt(byte[] data, String sKey) {
        try {
            byte[] key = sKey.getBytes();
            DESKeySpec desKey = new DESKeySpec(key);
            // 创建一个密匙工厂，然后用它把DESKeySpec转换成securekey
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
            SecretKey securekey = keyFactory.generateSecret(desKey);
            // Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance(CIPHER_PARAM);
            // 用密匙初始化Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, securekey);
            // 现在，获取数据并加密
            // 正式执行加密操作
            return cipher.doFinal(data);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * ECB模式解密 内部调用
     *
     * @param src
     * @param sKey
     * @return
     */
    private static byte[] decrypt(byte[] src, String sKey) {
        try {
            byte[] key = sKey.getBytes();
            // 创建一个DESKeySpec对象
            DESKeySpec desKey = new DESKeySpec(key);
            // 创建一个密匙工厂
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
            // 将DESKeySpec对象转换成SecretKey对象
            SecretKey securekey = keyFactory.generateSecret(desKey);
            // Cipher对象实际完成解密操作
            Cipher cipher = Cipher.getInstance(CIPHER_PARAM);
            // 用密匙初始化Cipher对象
            cipher.init(Cipher.DECRYPT_MODE, securekey);
            // 真正开始解密操作
            return cipher.doFinal(src);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    private static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

}
